// weather.js

/*  This page does all the work
 *  The city is sent to weather url 
 *  which will return data in xml format.
 */
 
// Have a function run after the page loads:
window.onload = init;

function appendLine(str, text)
{
	str = str + text + "<br>";
	return str;
}


// Function that adds the Ajax layer:
function init() 
{
	// Check for DOM support:
	if (document.getElementById('results')) 
	{
		// Log to results area:
		var results = document.getElementById('results');
		results.innerHTML = appendLine(results.innerHTML, "function init");
		results.innerHTML = appendLine(results.innerHTML, "");
		results.style.display = 'block';
	}

} // End of init() function.


function getWeather()
{
	// Get the city:
	var city = document.getElementById('city').value;
	
	// Open the connection:
	var url = "http://free.worldweatheronline.com/feed/weather.ashx?";
	url = url + "q=" + encodeURIComponent(city);
	url = url + "&format=xml";
	url = url + "&num_of_days=2";
	url = url + "&key=b473f3a3cb053219111108";
	
	// Get an XMLHttpRequest object:
	var ajax = getXMLHttpRequestObject();
	if (ajax) 
	{
		// Log to results area:
		var results = document.getElementById('results');
		results.innerHTML = appendLine(results.innerHTML, url);
		results.innerHTML = appendLine(results.innerHTML, "ajax.readyState:" + ajax.readyState);
		results.innerHTML = appendLine(results.innerHTML, "");

		ajax.open('get', url);
		
		// Function that handles the response:
		ajax.onreadystatechange = function() 
		{
			// Pass it this request object:
			handleResponse(ajax);
		}
	
		// Send the request:
		ajax.send(null);
	}

	return false; // So form isn't submitted.
	
} // End of ajax


// Function that handles the response from the PHP script:
function handleResponse(ajax) 
{
	var results = document.getElementById('results');
	results.innerHTML = appendLine(results.innerHTML, "function handleResponse");
	results.innerHTML = appendLine(results.innerHTML, "ajax.readyState:" + ajax.readyState);

	// Check that the transaction is complete:
	if ( ajax.readyState == 4 ) 
	{
		// Check for a valid HTTP status code:
		if ( (ajax.status == 200) || (ajax.status == 304) ) 
		{
			// Put the received response in the DOM:
			results.innerHTML = ajax.responseText;
		}
		else
		{ 
			// Bad status code, submit the form.
			//document.getElementById('weather_form').submit();
			results.innerHTML = appendLine(results.innerHTML, "ajax.status:" + ajax.status);
		}
	
	} // End of readyState IF.
		
	results.innerHTML = appendLine(results.innerHTML, "");

} // End of handleResponse() function.

